//
//  SearchTagViewController.m
//  reacticons
//
//  Created by Admin on 8/22/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SearchTagViewController.h"
#define CANCEL_BTN 11
@implementation SearchTagViewController

@synthesize tableData = _tableData;
@synthesize delegate = _delegate;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _tableData = [[NSMutableArray alloc] init];
        _searchData = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)dealloc
{
    if (_tableData) {
        _tableData = nil;
        [_tableData release];
    }
    if (_searchData) {
        _searchData = nil;
        [_searchData release];
    }
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _tableData=[_searchData mutableCopy];
    [_searchBar setText:@""];
    [_searchBar setPlaceholder:@"Search by tags"];
//    [_searchBar setShowsCancelButton:YES];
//    [_searchBar becomeFirstResponder];
    [_tableView reloadData];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)setTableData:(NSMutableArray *)tableData
{
    _tableData = [tableData mutableCopy];
    _searchData = [tableData mutableCopy];
}

#pragma mark - Table View Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableData.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * SearchTagCelID = @"SearchTagCelID";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:SearchTagCelID];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SearchTagCelID] autorelease];
    }
    
    [cell.textLabel setText:[_tableData objectAtIndex:indexPath.row]];
    [cell.textLabel setFont:[UIFont boldSystemFontOfSize:16]];
    
    return cell;
}

#pragma mark - Table View Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setSelected:NO];
    
    if ([_delegate respondsToSelector:@selector(searchTagViewController:didSelectTag:)]) 
    {
        [_delegate searchTagViewController:self didSelectTag:[_tableData objectAtIndex:indexPath.row]];
    }
    
    [self dismissModalViewControllerAnimated:NO];
}

#pragma mark - Search Bar Delegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar

{
//    searchBar.showsCancelButton = YES;
    searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar

{
    //    searchBar.showsCancelButton = NO;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSString * sText = [[NSString alloc] initWithFormat:@"%@",[searchText lowercaseString]];
    [_tableData removeAllObjects];// remove all data that belongs to previous search
    
    if([searchText isEqualToString:@""] || searchText==nil){
        
        [_tableView reloadData];
        
        return;
        
    }
    
    NSInteger counter = 0;
    
    for(NSString * tagName in _searchData)
    {
        
        NSString *str = [tagName lowercaseString];
        
        NSRange r = [str rangeOfString:sText];
        
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
        
        if(r.location != NSNotFound)
            
        {
            if(r.location == 0)//that is we are checking only the start of the names.
                
            {
                [_tableData addObject:tagName];
            }
            
        }
        
        counter ++;
        [pool release];
    }
    
    [sText release];
    
    
    [_tableView reloadData];
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    //    [self.navigationController popViewControllerAnimated:YES];
    [_tableData removeAllObjects];
    
    [_tableData addObjectsFromArray:_searchData];
    
    @try{
        [_tableView reloadData];
    }
    
    @catch(NSException *e){
        
    }
    
    [searchBar resignFirstResponder];
    
    searchBar.text = @"";
    [self dismissModalViewControllerAnimated:NO];
}

-(IBAction)clickedBtn:(id)sender{
    if ([sender tag]==CANCEL_BTN) {
        [self dismissModalViewControllerAnimated:YES];
    }
}

@end
